from godot import exposed, export
from godot.bindings import *
from random import randrange

def slightly_random(vec, delta):
    x = (vec.x + delta * randrange(-200, 200) * 0.01) * 1.05
    y = vec.y + delta * randrange(-200, 200) * 0.01
    V = Vector2(x, y)
    return V.normalized()

MIN_X = 100
MIN_Y = 0
MAX_X = 800 - MIN_X
MAX_Y = 600 - MIN_Y

@exposed
class fish_logic(Node2D):
    def _ready(self):
        self.trajectory = Vector2(0,1)
        self.speed = 50.0
        self.speed_p = 0.0
        self.speed_pp = 0.0
        self.set_process(True)

    def _process(self, delta):
        self.set_position(self.next_wander(delta))
    
    def next_wander(self, delta):
        current_pos = self.get_position()
        speed = self.speed
        speed_p = self.speed_p
        speed_pp = self.speed_pp
        trajectory = self.trajectory

        x = 0
        for i in range(20):
            x += randrange(-10, 10)

        speed_pp += delta * x

        if (current_pos.x < MIN_X and trajectory.x < 0 or current_pos.x > MAX_X and trajectory.x > 0):
            speed_pp = 0.0
            speed_p = -100.0
        
        if (current_pos.y < MIN_Y):
            trajectory.y = 1
        elif (current_pos.y > MAX_Y):
            trajectory.y = -1
        
        trajectory = slightly_random(trajectory, delta)

        if (speed < -0.2):
            speed = -speed * 2
            trajectory.x = -trajectory.x
            speed_p = 50
            speed_pp = 0
        if (speed > 110):
            speed = 100
            speed_p = -10
            speed_pp = 0

        if trajectory.x < -0.5:
            self.get_node("sprite").set_flip_h(False)
        elif trajectory.x > 0.5:
            self.get_node("sprite").set_flip_h(True)
        
        self.speed = speed
        self.speed_p = speed_p
        self.speed_pp = speed_pp
        self.trajectory = trajectory
        
        return self.get_position() + trajectory * speed * delta
